const db = require('./db')
const R = require('ramda')

const me = {
  list_by_pid: pid => {
    return new Promise((resolve, reject) => {
      db.query('select * from node where pid=?', [pid]).then(res => {
        if (R.isNil(res)) {
          resolve([])
        } else {
          console.log('获取nodes成功:')
          console.log(res)
          resolve(res)
        }
      })
    })
  },
  add_under: (pid, title, isArticle) => {
    return new Promise((resolve, reject) => {
      db.query(
        'insert into node(title,isArticle,create_time,pid) values(?,?,NOW(),?)',
        [title, isArticle, pid]
      ).then(res => {
        if(R.isNil(res)){
          console.log('好像失败了')
          resolve(false)
        }else{
          console.log('增加节点成功')
          console.log(res)
          resolve(true)
        }
      })
    })
  },
  get: id => {
    return new Promise((resolve,reject) => {
      db.query('select * from node where id=? limit 1',[id]).then(nodes => {
        resolve(nodes[0])
      })
    })
  },
  put: (id,title) => {
    return new Promise((resolve,reject) => {
      db.query('update node set title=? where id=?',[title,id]).then(result => {
        resolve(true)
      })
    })
  },
  del: id => {
    return new Promise((resolve,reject) => {
      db.query('delete from node where id=?',[id]).then(resolve)
    })
  }
}

module.exports = me